/*
* created by Administrator on 2018/12/12
* 好的代码像粥一样,是得用时间和精力熬的。
*/
const model = require('../database/model'); //数据库
const querystring = require('querystring');
const request = require('request'); //发送http请求
const Router = require('koa-router');   //路由中间件
const router = new Router();
router.get('/validCodeMsg', async (ctx, next) => {
    let {phoneNumber} = ctx.request.query; //es6 解构赋值
    if (phoneNumber && /^1[35789]\d{9}$/.test(phoneNumber)) {
        function random() {
            return parseInt(Math.random() * 1000000) + '';
        }

        let code = random();
        ctx.session.code = {
            code: code,
            tel: phoneNumber
        };
        ctx.session.user = {
            phoneNumber: String,
            password: String,
        };
        const querydata = querystring.stringify({
            mobile: phoneNumber,
            tpl_id: 121567,
            tpl_value: '#code#=' + code,
            key: '543a51a81319e96939e57d31213c61a7'
        });
        let url = `http://v.juhe.cn/sms/send?${querydata}`;
        let ajax = async (url) => {
            return new Promise((resolve, reject) => {
                request(url, (error, res, body) => {
                    let code = JSON.parse(body);
                    if (code.error_code === 0) {
                        resolve(code);
                    } else {
                        reject(code);
                    }
                })
            })
        };
        await ajax(url).then(() => {
            ctx.body = {
                code: 1,
                msg: `验证码已经发送到+86${phoneNumber}`
            };
        }).catch(() => {
            ctx.body = {
                code: -1,
                msg: '验证码发送失败'
            }
        })
    }
    await next();
});
//登录接口
router.post('/admin', async (ctx, next) => {

});
//注册接口
router.post('/reg', async (ctx, next) => {
    let {code,phoneNumber} = ctx.request.query; // es6 赋值解构
    if (ctx.session.code) {
        if (ctx.session.code.code === code &&ctx.session.code.phoneNumber===phoneNumber) {
           await  ctx.session.user.forEach(async (v) => {
               await models.User.create(v)
                   .then(data => {
                       console.log(data);
                       ctx.body = {
                           code: 1,
                           msg: '注册成功，写入数据',
                           data
                       }
                   })
                   .catch(error => {
                       ctx.body = {
                           code : -1,
                           msg : '注册失败,请多试几次',
                           error
                       };
                       console.log(error)
                   })
           });
        } else if (ctx.session.code.code !== code) {
            ctx.body = {
                code: -1,
                msg: '验证码输入有误'
            }
        }
    } else if(!ctx.session.code.code) {
        ctx.body = {
            code: -1,
            msg: '请先获取验证码'
        }
    }else if(!ctx.session.code.phoneNumber){
       ctx.body={
           code:-1,
           msg:'请输入手机号码'
       }
    }
    await next();
});
//登录接口
router.post('/login',async(ctx,next)=>{
    const {phoneNumber,password} =ctx.request.body;
    await model.User.find({PhoneNumber:phoneNumber,password:password}).count()
        .then((data=>{
        if(data>=1){
            ctx.body={
                code:1,
                msg:'登录成功！'
            }
        }else{
            ctx.body ={
                code: -1,
                msg :'用户不存在!'
            }
        }
    })).catch(error=>{
        ctx.body={
            code:-1,
            msg:'数据出了一点点问题,请多试几次',
            error
        }
        });
    await next()
});
module.exports = app => app.use(router.routes());
